<script setup lang="ts">
import ApexCharts from "apexcharts";
import { useAttrs, onMounted, reactive } from "vue";
import { plugCountDate, warnCountDate } from "@/api/modules/home/index";

const attr = useAttrs();
console.log("attr.remoteData", attr.remoteData);

function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === "string") {
      time = time.replace(new RegExp(/-/gm), "/");
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

function getLastSevenDays() {
  const dates = [];
  let today = new Date();
  today.setDate(today.getDate() + 1);
  // 获取中国标准时间 (UTC+8)
  const options = { timeZone: "Asia/Shanghai", year: "numeric", month: "2-digit", day: "2-digit" };

  for (let i = 1; i <= 7; i++) {
    const pastDate = new Date(today);
    // 设置日期为今天减去 i 天
    pastDate.setDate(today.getDate() - i);

    // 获取格式化日期
    const formattedDate = pastDate.toLocaleDateString("zh-CN", options).replace(/\//g, "-");
    dates.push(formattedDate);
  }

  return dates.reverse();
}

const times = getLastSevenDays();
const pageData = reactive({
  series: [],
  chartOptions: {
    chart: {
      type: "bar",
      height: 350,
      toolbar: {
        show: false
      }
    },
    plotOptions: {
      bar: {
        horizontal: false,
        columnWidth: "55%",
        borderRadius: 5,
        borderRadiusApplication: "end"
      }
    },
    legend: {
      show: true, // 显示图例
      position: "top" // 图例位置
    },
    dataLabels: {
      enabled: false
    },
    stroke: {
      show: true,
      width: 2,
      colors: ["transparent"]
    },
    colors: ["rgb(48, 50, 63)", "#a30c0c"],
    xaxis: {
      categories: times
    },
    yaxis: {
      title: {
        text: "次数"
      }
    },
    fill: {
      opacity: 1
    },
    tooltip: {
      y: {
        formatter: function (val) {
          return val + "次";
        }
      }
    }
  }
});
onMounted(async () => {
  const currentTimestamp = Date.now();
  // 计算7天的毫秒数
  const sevenDaysInMillis = currentTimestamp - 7 * 24 * 60 * 60 * 1000;
  const res1 = await plugCountDate({
    startTime: parseInt(sevenDaysInMillis / 1000),
    endTime: parseInt(currentTimestamp / 1000)
  });
  const res2 = await warnCountDate({
    startTime: parseInt(sevenDaysInMillis / 1000),
    endTime: parseInt(currentTimestamp / 1000)
  });
  const arrOne = times.map(val => {
    const dataIndex = res1.data.findIndex(item => item.date === val);
    if (dataIndex != -1) {
      return res1.data[dataIndex].num;
    }
    return 0;
  });
  const arrTwo = times.map(val => {
    const dataIndex = res2.data.findIndex(item => item.date === val);
    if (dataIndex != -1) {
      return res2.data[dataIndex].num;
    }
    return 0;
  });
  pageData.series = [
    {
      name: "封堵",
      data: arrOne
    },
    {
      name: "告警",
      data: arrTwo
    }
  ];
  console.log("res1", res1);
  console.log("res2", res2);
  console.log("pageData", pageData);
});
</script>
<template>
  <div>
    <h3 style="margin: 0px">告警封堵</h3>
    <div style="height: 350px">
      <apexchart
        v-if="pageData.series?.length"
        width="100%"
        height="350px"
        type="bar"
        :options="pageData.chartOptions"
        :series="pageData.series"
      ></apexchart>
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.apexcharts-legend) {
  justify-content: flex-end !important;
  width: 95%;
}
</style>
